'''
twitter_account.py
Nicholas Swartzendruber

This class is used as a wrapper for the twitter class.
The account is specified in constants.py.
'''

import time
import random

from twitter.api import Twitter, TwitterError
from twitter.oauth import OAuth, write_token_file, read_token_file
from twitter.oauth_dance import oauth_dance

from constants import *
from log import Log


class TwitterAccount:
  
  def __init__(self):
    '''
    Uses the details in constants.py to create a new
    twitter instance. TwitterAccount class is a wrapper
    for the twitter tools python twitter tools.
    '''
    self.twitter = Twitter(
            auth=OAuth(
                OAUTH_TOKEN, OAUTH_TOKEN_SECRET, 
                CONSUMER_KEY, CONSUMER_SECRET),
            secure=True,
            api_version='1',
            domain='api.twitter.com')
    
    self.targets = []
    self.friend = []
    followers = self.getFollowers()
    friends = self.getFriends()
    
    #Load all of the potential targets and those needing friended.
    with open('target_id.txt', 'r') as f:
      while 1:
        line = f.readline()
        if not line:
          break
        user = int(line.split('\n')[0])
        #Is the user our follower? No? Then they are a target.
        if user not in followers:
          self.targets.append(user)
          
        #Are we friends with the person yet? Are they already following us?
        if user not in friends and user not in followers:
          self.friend.append(user)
          
  def post(self, message):
    '''
    The given message will be posted on the account
    as configured in constants.py
    '''
    try:
      ret = self.twitter.statuses.update(status=str(message))
      Log.println("Sending tweet: " + str(message))
    except TwitterError as twitter_error:
      Log.println("Error " + str(twitter_error.e.code) + " when getting posting a tweet.")
      return None
    return ret
    
  def getFollowers(self):
    '''
    Returns the IDs of all the users that follow the account as a list.
    '''
    try:
      followers = self.twitter.followers.ids(screen_name=USER)
    except TwitterError as twitter_error:
      Log.println("Error " + str(twitter_error.e.code) + " when getting followers.")
      return None
    return followers
  
  def getFriends(self):
    '''
    Returns the IDs of all the users that are currently friends.
    '''
    try:
      friends = self.twitter.friends.ids(screen_name=USER)
    except TwitterError as twitter_error:
      Log.println("Error " + str(twitter_error.e.code) + " when getting friends.")
      return None
    return friends
  
  def refreshTargetsAndFriends(self):
    '''
    Called to refresh the possible targets and friends.
    Basically removes any follower that is also a target.
    '''
    Log.println("Refreshing potential targets.")
    followers = self.getFollowers()
    for follower in followers:
      if follower in self.targets:
        self.targets.remove(follower)
      if follower in self.friend:
        self.friends.remove(follower)
  
  def getNewTarget(self):
    '''
    Returns someone to target. MAY BE SAME PERSON
    ON REPEAT CALLS.
    '''
    if (len(self.targets)) > 0:
      target = random.choice(self.targets)
    else:
      target = False
    if target:
      Log.println("Grabbing new random target: " + self.getUsername(target))
    return target 
  
  def getNewFriend(self):
    '''
    Returns a new person to follow.
    '''
    if len(self.friend) > 0:
      friend = self.friend.pop()
    else:
      friend = False
    return friend
  
  def follow(self, uid):
    '''
    Follows the user as passed in user id.
    '''
    if type(uid) is str or type(uid) is int:
      
      try:
        ret = self.twitter.friendships.create(user_id=str(uid))
        Log.println("Following user: " + self.getUsername(uid))
      except TwitterError as twitter_error:
        Log.println("Error " + str(twitter_error.e.code) + " when getting following user.")
        return None
    else:
      return None
    return ret
    
  def getUsername(self, uid):
    user = str(uid)
    try:
      user = self.twitter.users.show(user_id=user)['screen_name']
    except TwitterError as twitter_error:
      Log.println("Error " + str(twitter_error.e.code) + " when getting getting a user name.")
      return None
    return user
  
  def getAuthInfo(self):
    try:
      info = self.twitter.account.rate_limit_status()
    except TwitterError as twitter_error:
      Log.println("Error " + str(twitter_error.e.code) + " when getting getting rate limit info.")
      return None
    return info 
  
  def getTwitterObject(self):
    return self.twitter
  
  def hasTargetsLeft(self):
    return len(self.targets) > 0
    
if __name__ == '__main__': 
  twitter = TwitterAccount()
  print twitter.getUsername(14611396)
  print twitter.getAuthInfo()
  print str(int(time.time()))
 